package com.rent.message.rabbit;

import com.rent.common.constant.CommonConstant;
import com.rent.message.pojo.entity.ChatMessage;
import com.rent.message.service.ChatMessageService;
import com.rent.message.utils.BatchProcessorFactory;
import com.rent.message.utils.DistributedBatchProcessor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

@Component
@Slf4j
public class ChatMessageMq {

    @Autowired
    private BatchProcessorFactory batchProcessorFactory;

    @Autowired
    private ChatMessageService chatMessageService;

    private DistributedBatchProcessor<ChatMessage> chatMessageProcessor;


    /**
     * 初始化批量处理器
     */
    @PostConstruct
    public void init() {
        log.info("=== ChatMessageMq 初始化 ===");
        chatMessageProcessor = batchProcessorFactory.getOrCreateProcessor(
                "chat-message-processor",
                100,
                10000L,
                this::batchSaveToDatabase
        );

        log.info("=== ChatMessageMq 初始化完成，processor: {} ===", chatMessageProcessor);
    }

    /**
     * 接收消息
     * @param message
     */
    @RabbitListener(queues = CommonConstant.CHAT_MESSAGE)
    public void receive(ChatMessage message){
        log.info("=== 接收到聊天消息，开始处理 ===");
        log.info("消息内容: {}", message);
        try {
            chatMessageProcessor.add(message);
            log.debug("接收到聊天消息，当前缓冲区大小: {}", chatMessageProcessor.getBufferSize());
        } catch (Exception e) {
            log.error("处理聊天消息失败: {}", message, e);
        }
    }

    /**
     * 批量保存到数据库
     */
    /**
     * 批量保存到数据库
     */
    private void batchSaveToDatabase(List<ChatMessage> messages) {
        if (messages.isEmpty()) {
            log.debug("批量保存聊天消息为空");
            return;
        }

        try {
            chatMessageService.batchSave(messages);
            log.info("批量保存了 {} 条聊天消息到数据库", messages.size());
        } catch (Exception e) {
            log.error("批量保存聊天消息失败，数量: {}", messages.size(), e);
            throw new RuntimeException("批量保存失败", e);
        }
    }

}
